from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models
from global_config import message
import json
import logging


def sendmessage(agent_arg, phone, templateid):
    try:
        # 实例化一个认证对象，入参需要传入腾讯云账户密钥对secretId，secretKey。
        cred = credential.Credential(message['secretId'], message['secretKey'])
        # 实例化要请求产品(以sms为例)的client对象
        client = sms_client.SmsClient(cred, "ap-beijing")
        # 实例化一个请求对象，根据调用的接口和实际情况，可以进一步设置请求参数
        req = models.SendSmsRequest()
        # 短信应用ID
        req.SmsSdkAppId = message['SmsSdkAppId']
        # 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名
        req.SignName = message['SignName']
        # 模板 ID: 必须填写已审核通过的模板 ID
        req.TemplateId = templateid
        # 模板参数
        req.TemplateParamSet = agent_arg
        # 下发手机号码
        req.PhoneNumberSet = ["+86" + phone]
        resp = client.SendSms(req)
        # 输出json格式的字符串回包
        return json.loads(resp.to_json_string(indent=2))["SendStatusSet"][0]["Code"]
    except TencentCloudSDKException as err:
        print(err)
        logging.error("短信功能异常!")
